﻿using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ZhuXingFamilys.ExportExcel.entity;
using ZhuXingFamilys.ExportExcel.utils;
using ZhuXingFamilys.ListComparison.Entity;
using ZhuXingFamilys.MainViewModel;
using System.Collections;

namespace ZhuXingFamilys.ListComparison
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class CompareMainWindow : Window
    {
        // BIM清单
        private ObservableCollection<excelEntity> bimqdList;
        // 造价清单
        private ObservableCollection<excelEntity> zjqdList;
        // 当前工程下BIM清单
        private ObservableCollection<excelEntity> curren_bimqdList = new ObservableCollection<excelEntity>();
        // 当前造价清单
        private ObservableCollection<excelEntity> curren_zjqdList = new ObservableCollection<excelEntity>();
        // 工程文件名称
        private string WJMC;
        // 匹配规则
        private List<string> selectValue;
        // 项目编码字典
        List<ProjectCodeDictionary> projectCodeDictionaries;
        public CompareMainWindow(string _GCQDFilePath, string _ZJQDFilePath, string _WJMC, List<string> _selectValue)
        {
            //ui库使用
            ColorZoneAssist.SetMode(new GroupBox(), ColorZoneMode.Light);
            Hue hue = new Hue("name", System.Windows.Media.Color.FromArgb(1, 2, 3, 4), System.Windows.Media.Color.FromArgb(1, 5, 6, 7));
            // 读取BIM工程清单
            bimqdList = ReadExcel(_GCQDFilePath);
            // 读取造价清单
            zjqdList = ReadExcel(_ZJQDFilePath);
            // 工程名称
            WJMC = _WJMC;
            // 匹配规则
            selectValue = _selectValue;
            // 获取项目编码字典
            projectCodeDictionaries = getProjectCodeDictionaries();

            InitializeComponent();
            // 窗口尺寸发生变化
            this.SizeChanged += new SizeChangedEventHandler(Winodw_Resize);
        }
        // 读取Excel转换实体
        private ObservableCollection<excelEntity> ReadExcel(string filePath)
        {
            string path = filePath;
            string fileName = path.Substring(path.LastIndexOf("\\") + 1);
            using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                byte[] bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                fileStream.Close();
                // 读取rules
                MemoryStream stream1 = new MemoryStream(bytes);
                ObservableCollection<excelEntity> excelEntityList = ExcelConvert.ToEntityStreamListForExcelData<excelEntity>(stream1, fileName, true);
                return excelEntityList;
            }
        }

        // 窗口尺寸变化界面调整
        private void Winodw_Resize(object sender, SizeChangedEventArgs e)
        {
            // 最大化
            if (this.WindowState == WindowState.Maximized)
            {
                double StackPanelWidth = 375;
                double x1 = SystemParameters.PrimaryScreenWidth;//得到屏幕整体宽度
                double y1 = SystemParameters.PrimaryScreenHeight;//得到屏幕整体高度
                // 左侧工程菜单尺寸
                ProjectTreeView.Width = 200;
                ProjectTreeView.Height = y1 - 50;
                // 右侧详细展示内容宽度
                StackPanel_zhanshi.Height = y1 - 50;
                // 分部分项表格尺寸
                ScrollViewer_FBFX.Width = x1 - StackPanelWidth;
                ScrollViewer_FBFX.Height = y1 - 175;
                // 措施项目表格尺寸
                ScrollViewer_CSXM.Width = x1 - StackPanelWidth;
                ScrollViewer_CSXM.Height = y1 - 175;

            }
            // 窗口化
            else if (this.WindowState == WindowState.Normal)
            {
                double StackPanelWidth = 390;
                // 左侧工程菜单尺寸
                ProjectTreeView.Width = 200;
                ProjectTreeView.Height = (this.Height - 50) > 0 ? (this.Height - 50) : 0;
                // 右侧详细展示内容宽度
                StackPanel_zhanshi.Height = (this.Height - 50) > 0 ? (this.Height - 50) : 0;
                // 分部分项表格尺寸
                ScrollViewer_FBFX.Width = (this.Width - StackPanelWidth) > 0 ? (this.Width - StackPanelWidth) : 0;
                ScrollViewer_FBFX.Height = (this.Height - 160) > 0 ? (this.Height - 160) : 0;
                // 措施项目表格尺寸
                ScrollViewer_CSXM.Width = (this.Width - StackPanelWidth) > 0 ? (this.Width - StackPanelWidth) : 0;
                ScrollViewer_CSXM.Height = (this.Height - 160) > 0 ? (this.Height - 160) : 0;

            }
        }

        private void CompareMainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {

            List<ProjectCodeDictionary> pros = new List<ProjectCodeDictionary>();
            ProjectCodeDictionary codeDictionary = new ProjectCodeDictionary();
            codeDictionary.ProjectCode = null;
            codeDictionary.ProjectName = WJMC + "分项工程";
            codeDictionary.Level = 0;
            codeDictionary.Children = projectCodeDictionaries;
            pros.Add(codeDictionary);
            ProjectTreeView.ItemsSource = pros;

            if (ProjectTreeView.Items.Count != 0)
            {
                // 展开第一个
                ProjectCodeDictionary ti = ProjectTreeView.Items[0] as ProjectCodeDictionary;
                DependencyObject dObject = ProjectTreeView.ItemContainerGenerator.ContainerFromItem(ti);
                ((TreeViewItem)dObject).IsExpanded = true;
            }
        }
        // 工程选项切换
        private void CategoryTreeView_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (IsLoaded)
            {
                ProjectCodeDictionary pcd = e.NewValue as ProjectCodeDictionary;
                if (pcd != null && pcd.Level == 1)
                {
                    curren_bimqdList.Clear();
                    curren_zjqdList.Clear();
                    // 处理分部分项BIM数据
                    string[] strings = Regex.Split(pcd.ProjectCode, ",");
                    foreach (string s in strings)
                    {
                        foreach (excelEntity excelEntity in bimqdList)
                        {
                            if (excelEntity.Code.StartsWith(s))
                            {
                                curren_bimqdList.Add(excelEntity);
                            }
                        }
                    }
                    // 分部分项BIM数据
                    this.FbfxBimExcel.ItemsSource = curren_bimqdList;
                    // 分部分项造价数据
                    this.FbfxZjExcel.ItemsSource = getZjqdListByRules(curren_bimqdList, zjqdList);
                    // 开启选项卡
                    TabControl_zhanshi.IsEnabled = true;
                }
                else
                {
                    // 关闭选项卡
                    TabControl_zhanshi.IsEnabled = false;
                }
                // var item = e.NewValue as System.Windows.Controls.TreeViewItem;
                // this.GCID.Text = "001";
                // this.GCMC.Text = item.Header.ToString();
                // this.QDZY.Text = "test";
            }
        }

        // 选项切换
        private void Selector_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        // 根据BIM清单数据和匹配规则 生成造价清单数据
        private ObservableCollection<excelEntity> getZjqdListByRules(ObservableCollection<excelEntity> list1, ObservableCollection<excelEntity> list2)
        {
            excelEntity nullEntity = new excelEntity();
            nullEntity.Code = "";
            ObservableCollection<excelEntity> reList = new ObservableCollection<excelEntity>();
            if (selectValue.Count == 1 && selectValue.Contains("规则1"))
            {
                for (int i = 0; i < list1.Count; i++)
                {
                    var list1Code = list1[i].Code;
                    var excelEntity = list2.Where(l => l.Code.Equals(list1Code)).FirstOrDefault();
                    if (excelEntity != null)
                        reList.Insert(i, excelEntity);
                    else
                        reList.Insert(i, nullEntity);
                }
            }
            if (selectValue.Count == 2 && selectValue.Contains("规则1") && selectValue.Contains("规则3"))
            {
                for (int i = 0; i < list1.Count; i++)
                {
                    var list1Code = list1[i].Code;
                    var name = list1[i].Name;
                    var excelEntity = list2.Where(l => l.Code.Equals(list1Code) && l.Name.Equals(name)).FirstOrDefault();
                    if (excelEntity != null)
                        reList.Insert(i, excelEntity);
                    else
                        reList.Insert(i, nullEntity);
                }
            }
            if (selectValue.Count == 2 && selectValue.Contains("规则1") && selectValue.Contains("规则4"))
            {
                for (int i = 0; i < list1.Count; i++)
                {
                    var list1Code = list1[i].Code;
                    var features = list1[i].Features;
                    var excelEntity = list2.Where(l => l.Code.Equals(list1Code) && l.Features.Equals(features)).FirstOrDefault();
                    if (excelEntity != null)
                        reList.Insert(i, excelEntity);
                    else
                        reList.Insert(i, nullEntity);

                }
            }
            if (selectValue.Count == 3 && selectValue.Contains("规则1") && selectValue.Contains("规则3") && selectValue.Contains("规则4"))
            {
                for (int i = 0; i < list1.Count; i++)
                {
                    var list1Code = list1[i].Code;
                    var name = list1[i].Name;
                    var features = list1[i].Features;
                    var excelEntity = list2.Where(l => l.Code.Equals(list1Code) && l.Name.Equals(name) && l.Features.Equals(features)).FirstOrDefault();
                    if (excelEntity != null)
                        reList.Insert(i, excelEntity);
                    else
                        reList.Insert(i, nullEntity);
                }
            }
            // if (selectValue.Count == 1 && selectValue.Contains("规则2"))
            // {
            //     for (int i = 0; i < list1.Count; i++)
            //     {
            //         var list1Code = list1[i].Code;
            //         var excelEntity = list2.Where(l => l.Code.StartsWith(list1Code.Substring(0,8))).FirstOrDefault();
            //         reList.Insert(i, excelEntity);
            //     }
            // }
            return reList;
        }

        //查询项目编号字典
        DataSet dataSet = new DataSet();
        private List<ProjectCodeDictionary> getProjectCodeDictionaries()
        {
            try
            {
                string constr = "server=8.142.144.242;database=BIMDataBase;uid=sa;pwd=1qazZSE$";
                string FamilySql = "select [ID],[ProjectCode],[ProjectName],[Level] from ProjectCodeDictionary";
                using (SqlConnection conn = new SqlConnection(constr))
                {
                    conn.Open();
                    SqlDataAdapter FamilyData = new SqlDataAdapter(FamilySql, conn);   //(查询语句和连接工具)
                    FamilyData.Fill(dataSet);    //将适配器数据存入DataSet工具中
                    List<ProjectCodeDictionary> projectCodeDictionaries = new List<ProjectCodeDictionary>();
                    ProjectCodeDictionary projectCodeDictionary = null;
                    foreach (DataRow row in dataSet.Tables[0].Rows)
                    {
                        projectCodeDictionary = new ProjectCodeDictionary();
                        projectCodeDictionary.ID = DataProcessor.ToValue(row, "ID", 0);
                        projectCodeDictionary.ProjectName = DataProcessor.ToValue(row, "ProjectName", "0");
                        projectCodeDictionary.ProjectCode = DataProcessor.ToValue(row, "ProjectCode", "0");
                        projectCodeDictionary.Level = DataProcessor.ToValue(row, "Level", 0);
                        projectCodeDictionaries.Add(projectCodeDictionary);
                    }
                    return projectCodeDictionaries;
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
            return null;
        }
    }
}
